package org.xsk.network.tcp.thread;

import org.xsk.network.tcp.object.User;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * description:
 * <p>
 * date: 2021/6/10 13:04
 * author: x-one
 */
public class MyThread extends Thread{

    private Socket socket;

    public MyThread(Socket socket){
        this.socket = socket;
    }

    public void run(){
        InputStream is=null;
        ObjectInputStream ois=null;
        OutputStream os=null;
        try {
            is = socket.getInputStream();
            ois = new ObjectInputStream(is);
            User user=(User) ois.readObject();
            System.out.println(user);

            os=socket.getOutputStream();
            String reply ="我是服务器，欢迎登陆" + user.toString();
            os.write(reply.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {

            //关闭资源
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
